// 权限拦截

import router from '_router'
import store from '_store'
import { Message } from 'element-ui'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css' // 加载条样式
import { getToken } from '../utils/auth'

nProgress.configure({ showSpinner: false })

// 白名单
const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  nProgress.start()

  const hasToken = getToken()
  // 如果有token
  if (hasToken) {
    // 登录了直接去首页
    if (to.path === '/login') {
      next({ path: '/' })
      nProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      // 获取角色信息
      // 有角色信息就直接过 没有就去请求用户信息
      if (hasRoles) {
        next()
      } else {
        try {
          const { roles } = await store.dispatch('user/getInfo') // 拉去用户信息

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles) // 生成可以访问的路由表
          console.log(accessRoutes)
          // dynamically add accessible routes
          // router.addRoutes(accessRoutes) // 合并路由
          accessRoutes.forEach(item => {
            router.addRoute(item)
          })
          // addRoutevue-router4 支持的方法 传入单个值 addRoutes传入数组
          next({ ...to, replace: true })
          console.log(25)
        } catch (error) {
          console.log('catch触发了')
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next('/login')
          nProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
      nProgress.done()
    } else {
      console.log(to.path)
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  nProgress.done()
})
